package com.Pure;

import android.graphics.Point;

import com.e3roid.E3Activity;
import com.e3roid.script.javascript.JavaScriptEngine;
import org.mozilla.javascript.NativeArray;
import com.Pure.PureLevel;
public class PureLevelLoader {
	public static void loadAgain(String filename,PureLevel level,E3Activity main)
	{
		level.pause();
		JavaScriptEngine jsEngine = JavaScriptEngine.loadFromAsset(filename, main);
		
		for(int i = 0;i<10;i++)
			for(int j = 0;j<13;j++)
				level.getGrid().removeItemByGridIndex(i, j);
		
		loadGrid( level, jsEngine);
		
		level.onLevelLoaded();
		level.resume();
		
	}
	public static PureLevel loadFromFile(String filename,E3Activity main)
	{
		JavaScriptEngine jsEngine = JavaScriptEngine.loadFromAsset(filename, main);
		PureLevel level = new PureLevel();
		((PureMain)main).level = level;
		
		loadGrid( level, jsEngine);
		level.onLevelLoaded();
		return level;
		
	}
	private static void loadGrid(PureLevel level,JavaScriptEngine jsEngine)
	{
		
		NativeArray gridContainer = (NativeArray)jsEngine.get("gridContainer");
		NativeArray row;
		
		gridContainer.getLength();
		for(int i = 0;i<gridContainer.getLength();i++)
		{
			row = (NativeArray)gridContainer.get(i, gridContainer);
			String gameObject = new String();
			
			for(int j = 0; j < row.getLength();j++)
			{
				gameObject = (String)row.get(j, row);
				processGameObjectToLevel(level,gameObject,j,i);
			}
			//System.out.println(printout);
		}
	}
	
	//"V" load a Vempire
	//"B" load a Block
	//"M" load a Mirror
	public static void processGameObjectToLevel(PureLevel level,String gameObject,int x,int y)
	{
		
		
		
		PureGameObject object = null;
		PureGameFactory factory = PureMain.getInstance().factory;
		PureGrid grid = level.getGrid();
		
		
		if(gameObject.equals("V")){
			object = factory.createVempire(0, 0);	
		}else if(gameObject.equals("B"))
		{
			object = factory.createBlock(0, 0);
		}else if(gameObject.equals("M"))
		{
			object = factory.createMirror(0, 0, 0);
		}else if(gameObject.equals("S>"))
		{
			object = factory.createLightSource(x, y, PureLightDirection.LD_RIGHT);
		}else if(gameObject.equals("S^"))
		{
			object = factory.createLightSource(x, y, PureLightDirection.LD_UP);
		}else if(gameObject.equals("S<"))
		{
			object = factory.createLightSource(x, y, PureLightDirection.LD_LEFT);
		}else if(gameObject.equals("Sv"))
		{
			object = factory.createLightSource(x, y, PureLightDirection.LD_DOWN);
		}
		
		if(object != null){
			grid.addItemByGridIndex(object, new Point(x, y));
		}
	}
}
